import time
import requests
from datetime import datetime
from lxml import etree

def find_latest_date_in_range(date_list, start_date, end_date):
    # 将字符串日期转换为datetime对象
    date_objects = [datetime.strptime(date_str, '%Y-%m-%d') for date_str in date_list]
    start_obj = datetime.strptime(start_date, '%Y-%m-%d')
    end_obj = datetime.strptime(end_date, '%Y-%m-%d')

    # 筛选时间范围内的日期
    filtered_dates = [date for date in date_objects if start_obj <= date <= end_obj]

    # 如果有符合条件的日期，返回所有符合条件的日期（格式化为字符串）
    if filtered_dates:
        return [date.strftime('%Y-%m-%d') for date in filtered_dates]
    else:
        print(f"{start_date} 00:00:00-{end_date} 00:00:00无随访记录")
        return None


def suifangdownload1(id_person,ehrid, headers_8,DOMAIN,start_limit_time,end_limit_time):

    url_1 = f"{DOMAIN}/phis/app/svc/flw/chronic"

    data = {
        'search_EQ_ehrId': f'{ehrid}',
        '_dch': f"{time.time()}".replace(".", "")[:13],
    }

    response_9 = requests.post(url_1, data=data, headers=headers_8)
    all_sf_info = []
    li_jibing = response_9.json()
    if li_jibing == []:
        return "没有慢病随访按钮"
    for date in li_jibing:
        all_sf_info.append(date["dateCreated"])
    target_date_list = find_latest_date_in_range(all_sf_info, start_limit_time, end_limit_time)
    if target_date_list==None:
        return []

    all_infomation = []
    list_riqibianshi = []
    try:
        for target_date in target_date_list:
            if target_date:
                for info in response_9.json():
                    # 限制条件，获取指定日期数据
                    if info["dateCreated"] == target_date:
                        suifang_data = {
                            '身份证号': "'"+str(id_person),
                            '随访类型': None,
                            '随访日期': None,
                            '此次随访分类': None,
                            '低血糖反应': None,
                            '血压随访分类': None,
                            '血糖随访分类': None,
                            '症状': None,
                            '症状编辑框': None,
                            '随访机构': None,
                            '随访人': None,
                            '随访方式': None,
                            '是否加入国家标准版': None,
                            '姓名': None,
                            '性别': None,
                            '出生日期': None,
                            '所属人群': None,
                            '慢病类型': None,
                            '其他慢病合并症': None,
                            '服药依从性': None,
                            '药物不良反应': None,
                            '药物不良反应描述': None,
                            '下次随访日期': None,
                            '身高': None,
                            '收缩压': None,
                            '舒张压': None,
                            '体重': None,
                            '目标体重': None,
                            '体质指数(BMI)': None,
                            '目标体质指数(BMI)': None,
                            '心率': None,
                            '目标心率': None,
                            '足背动脉搏动触及正常': None,
                            '足背动脉搏动减弱': None,
                            '足背动脉搏动消失': None,
                            '其他体征': None,
                            '日吸烟量': None,
                            '目标日吸烟量': None,
                            '日饮酒量': None,
                            '目标日饮酒量': None,
                            '运动次数': None,
                            '目标运动次数': None,
                            '运动时间': None,
                            '目标运动时间': None,
                            '主食量': None,
                            '目标主食量': None,
                            '空腹血糖': None,
                            '餐后血糖': None,
                            '糖化血红蛋白': None,
                            '糖化血红蛋白日期': None,
                            'TC': None,
                            'TG': None,
                            'HDL-C': None,
                            'LDL-C': None,
                            'BUN': None,
                            'Cr': None,
                            '肌酐清除率': None,
                            '尿检': None,
                            '尿微量白蛋白': None,
                            '心电图': None,
                            '眼底': None,
                            '其他辅助检查': None,
                            '是否糖尿病': None,
                            '是否老年人': None,
                            '是否咳嗽、咳痰2周': None,
                            '是否痰中带血或咯血': None,
                            '转诊原因': None,
                            '机构及科别': None,
                            '评估': None,
                            '生活方式': None,
                            '医生建议': None,
                            '用药情况': None
                        }


                        # 随访类型
                        suifangleixing_list = ["高血压","糖尿病","高血压,糖尿病"]
                        try:
                            suifang_data["随访类型"] = suifangleixing_list[int(info.get("chronicType", -1))-1]
                        except IndexError as index_error:
                            print("随访类型错误:", index_error)
                            suifang_data["随访类型"] = None
                        except Exception as e:
                            suifang_data["随访类型"] = "获取失败"
                        data_id = info.get("id")

                        if data_id in list_riqibianshi:
                            continue
                        list_riqibianshi.append(data_id)




                        # 提取需要的数据
                        suifang_data["随访日期"] = info.get("dateCreated")
                        if suifang_data["随访类型"] == "高血压,糖尿病":



                            # 低血糖反应
                            dixuetang = ['无' , '偶尔' , '频繁']
                            try:
                                suifang_data["低血糖反应"] = dixuetang[int(info.get("hypoglycemia", -1))-1]
                            except IndexError as index_error:
                                print("低血糖反应错误:", index_error)
                                suifang_data["低血糖反应"] = None
                            except Exception as e:
                                suifang_data["低血糖反应"] = "获取失败"

                            suifangfenlei = ['控制满意', '控制不满意', '不良反应', '并发症']
                            # 血压随访分类
                            try:
                                suifang_data["血压随访分类"] = suifangfenlei[int(info.get("flwSortBp", -1))-1]
                            except IndexError as index_error:
                                print("血压随访分类错误:", index_error)
                                suifang_data["血压随访分类"] = None
                            except Exception as e:
                                suifang_data["血压随访分类"] = "获取失败"

                            # 血糖随访分类
                            try:
                                suifang_data["血糖随访分类"] = suifangfenlei[int(info.get("flwSortBg", -1))-1]
                            except IndexError as index_error:
                                print("血糖随访分类错误:", index_error)
                                suifang_data["血糖随访分类"] = None
                            except Exception as e:
                                suifang_data["血糖随访分类"] = "获取失败"

                        # 症状
                        zhengzhuang_list = ['无症状，' ,   '头痛头晕，'   , '恶心呕吐，'   , '眼花耳鸣，'   , '呼吸困难，' ,   '心悸胸闷，' ,  '鼻衄出血不止，' ,   '四肢发麻，' ,   '下肢水肿，' ,'多饮，'  ,  '多食，'  ,  '多尿，'   , '视力模糊，'  ,  '感染，'   , '手脚麻木，'  ,  '体重明显下降，' ,"其他，"  ]
                        str_zhengzhuang =  ""
                        zhengzhuang_str = info.get("symptom")
                        try:
                            if zhengzhuang_str is not None:
                                list_zhengzhuang_str = zhengzhuang_str.strip(",").split(",")
                                for zhengzhuang_id in list_zhengzhuang_str:
                                    str_zhengzhuang+=zhengzhuang_list[int(zhengzhuang_id)-1]
                                suifang_data["症状"] = str_zhengzhuang
                            else:
                                suifang_data["症状"] = None
                        except:
                            suifang_data["症状"] = "获取失败"


                        # 随访方式
                        suifangfangshi = ["门诊","家庭","电话"]
                        try:
                            suifang_data["随访方式"] = suifangfangshi[int(info.get("followWay", -1))-1]
                        except IndexError as index_error:
                            print("随访方式错误:", index_error)
                            suifang_data["随访方式"] = None
                        except Exception as e:
                            suifang_data["随访方式"] = "获取失败"

                        # 随访机构
                        try:
                            suifang_data["随访机构"] = info.get("flwOrgName")
                        except Exception as e:
                            suifang_data["随访机构"] = "获取失败"


                        # 慢病类型
                        manbingleixing_list = ["高血压","糖尿病","高血压、糖尿病"]
                        try:
                            suifang_data["慢病类型"] = manbingleixing_list[int(info.get("chronicType", -1))-1]
                        except IndexError as index_error:
                            print("慢病类型错误:", index_error)
                            suifang_data["慢病类型"] = None
                        except Exception as e:
                            suifang_data["慢病类型"] = "获取失败"


                        # 其他慢病合并症
                        try:
                            suifang_data["其他慢病合并症"] = info.get("otherCombinationDisease")
                            if info.get("otherCombinationDisease") == "无":
                                suifang_data["其他慢病合并症"] = None
                        except IndexError as index_error:
                            print("其他慢病合并症错误:", index_error)
                            suifang_data["其他慢病合并症"] = None
                        except Exception as e:
                            suifang_data["其他慢病合并症"] = "获取失败"

                        # 服药依从性
                        fuyaoyicongxing_list = ['规律' , '间断' , '不服药' ]
                        try:
                            suifang_data["服药依从性"] = fuyaoyicongxing_list[int(info.get("followBehavior", -1))-1]
                        except IndexError as index_error:
                            print("服药依从性错误:", index_error)
                            suifang_data["服药依从性"] = None
                        except Exception as e:
                            suifang_data["服药依从性"] = "获取失败"

                        # 药物不良反应
                        yaowubuliangfanying_list = ['无' , '有' ]
                        try:
                            suifang_data["药物不良反应"] = yaowubuliangfanying_list[int(info.get("adverseReaction", -1))-1]
                        except IndexError as index_error:
                            print("药物不良反应错误:", index_error)
                            suifang_data["药物不良反应"] = None
                        except Exception as e:
                            suifang_data["药物不良反应"] = "获取出错"

                        try:
                            suifang_data["下次随访日期"] = info.get("nextFlwDate")
                        except Exception as e:
                            suifang_data["下次随访日期"] = "获取出错"



                        try:
                            suifang_data["收缩压"] = info.get("sbp")
                        except Exception as e:
                            suifang_data["收缩压"] = "获取出错"


                        try:
                            suifang_data["舒张压"] = info.get("dbp")
                        except Exception as e:
                            suifang_data["舒张压"] = "获取出错"


                        try:
                            suifang_data["体重"] = info.get("weightCur")
                        except Exception as e:
                            suifang_data["体重"] = "获取出错"

                        try:
                            suifang_data["目标体重"] = info.get("weightTar")
                        except Exception as e:
                            suifang_data["目标体重"] = "获取出错"

                        try:
                            suifang_data["体质指数(BMI)"] = info.get("bmiCur")
                        except Exception as e:
                            suifang_data["体质指数(BMI)"] = "获取出错"

                        try:
                            suifang_data["目标体质指数(BMI)"] = info.get("bmiTar")
                        except Exception as e:
                            suifang_data["目标体质指数(BMI)"] = "获取出错"

                        # 随访心率获取
                        if "高血压" in suifang_data["慢病类型"]:
                            try:
                                suifang_data["心率"] = info.get("heartRateCur")
                                if int(info.get("heartRateCur")) == -1:
                                    suifang_data["心率"] = None
                                    suifang_data["目标心率"] = None
                            except Exception as e:
                                suifang_data["心率"] = "获取出错"

                            try:
                                suifang_data["目标心率"] = info.get("heartRateTar")
                                if int(info.get("heartRateTar")) == -1:
                                    suifang_data["心率"] = None
                                    suifang_data["目标心率"] = None
                            except Exception as e:
                                suifang_data["目标心率"] = "获取出错"
                        else:
                            suifang_data["心率"] = None
                            suifang_data["目标心率"] = None


                        # 其他体征
                        try:
                            suifang_data["其他体征"] = info.get("otherSign")
                        except Exception as e:
                            suifang_data["其他体征"] = "获取出错"


                        try:
                            suifang_data["日吸烟量"] = info.get("smAmountCur")
                        except:
                            suifang_data["日吸烟量"] = "获取出错"
                        try:
                            suifang_data["目标日吸烟量"] = info.get("smAmountTar")
                        except:
                            suifang_data["目标日吸烟量"] ="获取出错"

                        try:
                            suifang_data["日饮酒量"] = info.get("dkAmountCur")
                        except:
                            suifang_data["日饮酒量"] = "获取出错"

                        try:
                            suifang_data["目标日饮酒量"] = info.get("dkAmountTar")
                        except:
                            suifang_data["目标日饮酒量"] = "获取出错"

                        #运动次数
                        try:
                            suifang_data["运动次数"] = info.get("exCycleCur")
                        except:
                            suifang_data["运动次数"] = "获取出错"
                        # 目标运动次数
                        try:
                            suifang_data["目标运动次数"] = info.get("exCycleTar")
                        except:
                            suifang_data["目标运动次数"] = "获取出错"
                        # 运动时间
                        try:
                            suifang_data["运动时间"] = info.get("exTimeCur")
                        except:
                            suifang_data["运动时间"] = "获取出错"
                        # 目标运动时间
                        try:
                            suifang_data["目标运动时间"] = info.get("exTimeTar")
                        except:
                            suifang_data["目标运动时间"] = "获取出错"
                        if "糖尿病" in suifang_data["慢病类型"]:
                            try:
                                suifang_data["主食量"] = info.get("fhAmountCur")
                                if suifang_data["主食量"] == -1:
                                    suifang_data["主食量"] = None
                            except:
                                suifang_data["主食量"] = "获取出错"

                            try:
                                suifang_data["目标主食量"] = info.get("fhAmountTar")
                                if suifang_data["目标主食量"] == -1:
                                    suifang_data["目标主食量"] = None
                            except:
                                suifang_data["目标主食量"] = "获取出错"
                        else:
                            suifang_data["主食量"] = None
                            suifang_data["目标主食量"] = None


                        if "糖尿病" in suifang_data["随访类型"]:
                            try:
                                suifang_data["空腹血糖"] = info.get("fbg")
                                if suifang_data["空腹血糖"] == -1:
                                    suifang_data["空腹血糖"] = "未查"
                            except:
                                suifang_data["空腹血糖"] = "获取出错"
                        if "糖尿病" in suifang_data["随访类型"]:
                            try:
                                suifang_data["餐后血糖"] = info.get("pbg")
                                if suifang_data["餐后血糖"] == -1 and "糖尿病" in suifang_data["随访类型"]:
                                    suifang_data["餐后血糖"] = "未查"
                                elif suifang_data["餐后血糖"] == -1:
                                    suifang_data["餐后血糖"] = None
                            except:
                                suifang_data["餐后血糖"] = "获取出错"

                        if "高血压" == suifang_data["慢病类型"]:
                            suifang_data["空腹血糖"] = "未查"
                            suifang_data["餐后血糖"] = "未查"

                        try:
                            suifang_data["糖化血红蛋白"] = info.get("hba1c")
                            if suifang_data["糖化血红蛋白"] == -1 and "糖尿病" in suifang_data["随访类型"]:
                                suifang_data["糖化血红蛋白"] = "未查"
                            elif suifang_data["糖化血红蛋白"] == -1:
                                suifang_data["糖化血红蛋白"] = None
                        except:
                            suifang_data["糖化血红蛋白"] = "获取出错"


                        try:
                            suifang_data["糖化血红蛋白日期"] = info.get("hba1cDate")
                        except:
                            suifang_data["糖化血红蛋白日期"] = "获取出错"


                        heads = [("TC", "tc"), ("TG", "tg"), ('HDL-C', "hdlC"), ("LDL-C", "ldlC"), ("BUN","bun"), ("Cr","cr"), ("肌酐清除率","ccr")]
                        for head in heads:
                            try:
                                suifang_data[head[0]] = info.get(head[1])
                                if suifang_data[head[0]] == -1:
                                    suifang_data[head[0]] = "未查"
                            except:
                                suifang_data[head[0]] = "获取出错"

                        # 尿检
                        try:
                            suifang_data["尿检"] = info.get("uran")
                        except:
                                suifang_data["尿检"] = "获取出错"

                        # 尿微量白蛋白
                        try:
                            suifang_data["尿微量白蛋白"] = info.get("malb")
                            if suifang_data["尿微量白蛋白"] == -1:
                                suifang_data["尿微量白蛋白"] = "未查"
                        except:
                            suifang_data["尿微量白蛋白"] = "获取出错"

                        # 心电图
                        try:
                            suifang_data["心电图"] = info.get("ecg")
                        except:
                            suifang_data["心电图"] = "获取出错"

                        # 眼底检查
                        try:
                            suifang_data["眼底"] = info.get("fundusOculi")
                        except:
                            suifang_data["眼底"] = "获取出错"

                        # 其他检查
                        try:
                            suifang_data["其他辅助检查"] = info.get("otherTest")
                        except:
                            suifang_data["其他辅助检查"] = "获取出错"


                        # 转诊原因
                        try:
                            suifang_data["转诊原因"] = info.get("referralReason","无")
                        except:
                            suifang_data["转诊原因"] = "获取出错"

                        # 机构及科别
                        try:
                            suifang_data["机构及科别"] = info.get("referralOrgDept","无")
                        except:
                            suifang_data["机构及科别"] = "获取出错"

                        # 此次随访分类
                        cicisuifangfenlei = ['控制满意', '控制不满意', '不良反应', '并发症']
                        if "高血压" == suifang_data["慢病类型"]:
                            try:
                                cicisuifangfenlei_id = info.get("flwSortBp","高血压患者未获取到这个")
                                suifang_data["此次随访分类"] = cicisuifangfenlei[int(cicisuifangfenlei_id) - 1]
                            except:
                                suifang_data["此次随访分类"] = "获取出错"
                        if "糖尿病" == suifang_data["慢病类型"]:
                            try:
                                cicisuifangfenlei_id = info.get("flwSortBg","糖尿病患者未获取到这个")
                                suifang_data["此次随访分类"] = cicisuifangfenlei[int(cicisuifangfenlei_id) - 1]
                            except:
                                suifang_data["此次随访分类"] = "获取出错"
                        # 此次随访分类
                        if suifang_data["随访类型"] == "高血压,糖尿病":
                            suifang_data["此次随访分类"] = None


                        print(f"数据获取到机构及科别处，模块1")

                        shengyv_data_url = f"{DOMAIN}/phis/app/svc/flw/chronic/update/{data_id}"
                        response2 = requests.get(shengyv_data_url, headers=headers_8).text

                        tree = etree.HTML(response2)


                        # 症状编辑框
                        try:
                            zhengzhuangbianjikuang = tree.xpath('//textarea[@id="otherSymptom_text"]/text()')[0]
                            suifang_data["症状编辑框"] = zhengzhuangbianjikuang
                        except IndexError as e:
                            suifang_data["症状编辑框"] = None

                        # 随访人
                        try:
                            suifangren = tree.xpath('//input[@id="followPerson"]/@value')[0]
                            suifang_data["随访人"] = suifangren
                        except:
                            suifang_data["随访人"] = "获取出错"

                        # 是否国家标准版
                        try:
                            guojiaban = tree.xpath('//input[@name="isGj"]/@value')[0]
                            suifang_data["是否加入国家标准版"] = ["是" if guojiaban == "1" else "否"][0]
                        except:
                            suifang_data["是否加入国家标准版"] = "获取出错"

                        # 使用following-sibling定位特定标签后的input元素
                        try:
                            name = tree.xpath('//span[contains(text(),"姓名：")]/following-sibling::input[1]/@value')[0]
                            suifang_data["姓名"] = name
                        except:
                            suifang_data["姓名"] = "获取失败"

                        try:
                            gender = tree.xpath('//span[contains(text(),"性别：")]/following-sibling::input[1]/@value')[0]
                            suifang_data["性别"] = gender
                        except:
                            suifang_data["性别"] = "获取失败"

                        try:
                            birth_date = tree.xpath('//span[contains(text(),"出生日期：")]/following-sibling::input[1]/@value')[
                                0]
                            suifang_data["出生日期"] = birth_date
                        except:
                            suifang_data["出生日期"] = "获取失败"

                        try:
                            population = tree.xpath('//span[contains(text(),"所属人群：")]/following-sibling::input[1]/@value')[
                                0]
                            suifang_data["所属人群"] = population
                        except:
                            suifang_data["所属人群"] = "获取失败"



                        # 药物不良反应
                        try:
                            untoward_effect_des = tree.xpath('//input[@id="untowardEffectDes"]/@value')[0]
                            suifang_data["药物不良反应描述"] = untoward_effect_des
                        except IndexError:
                            # 如果没有value属性或为空，则设置为None
                            suifang_data["药物不良反应描述"] = None
                        except Exception as e:
                            suifang_data["药物不良反应描述"] = "获取失败"

                        # 身高
                        try:
                            height = tree.xpath('//input[@id="height"]/@value')[0]
                            height_value = int(float(str(height)))
                            suifang_data["身高"] = height_value if height_value else None
                        except IndexError:
                            suifang_data["身高"] = None
                        except Exception as e:
                            suifang_data["身高"] = "获取失败"

                        # 足背动脉搏动触及正常
                        if "糖尿病" in suifang_data["随访类型"]:
                            try:
                                # 获取选中的"触及正常"选项
                                normal_selected = tree.xpath('//input[@name="dorsalisPedis" and @checked="checked"]/@value')
                                if normal_selected:
                                    normal_value = normal_selected[0]
                                    # 根据value值确定选中的是"是"还是"否"
                                    if normal_value == "2":
                                        suifang_data["足背动脉搏动触及正常"] = "是"
                                    elif normal_value == "1":
                                        suifang_data["足背动脉搏动触及正常"] = "否"
                                else:
                                    suifang_data["足背动脉搏动触及正常"] = None
                            except:
                                suifang_data["足背动脉搏动触及正常"] = "获取出错"

                            try:
                                # 获取选中的"减弱"选项
                                weaken_selected = tree.xpath(
                                    '//input[@name="dorsalisPedisWeaken" and @checked="checked"]/@value')
                                weaken_text = ""
                                if weaken_selected:
                                    weaken_value = weaken_selected[0]
                                    if weaken_value == "1":
                                        weaken_text = "双侧"
                                    elif weaken_value == "2":
                                        weaken_text = "左侧"
                                    elif weaken_value == "3":
                                        weaken_text = "右侧"
                                suifang_data["足背动脉搏动减弱"] = weaken_text if weaken_text else None
                            except:
                                suifang_data["足背动脉搏动减弱"] = "获取出错"

                            try:
                                # 获取选中的"消失"选项
                                disappear_selected = tree.xpath(
                                    '//input[@name="dorsalisPedisDisappear" and @checked="checked"]/@value')
                                disappear_text = ""
                                if disappear_selected:
                                    disappear_value = disappear_selected[0]
                                    if disappear_value == "1":
                                        disappear_text = "双侧"
                                    elif disappear_value == "2":
                                        disappear_text = "左侧"
                                    elif disappear_value == "3":
                                        disappear_text = "右侧"
                                suifang_data["足背动脉搏动消失"] = disappear_text if disappear_text else None
                            except:
                                suifang_data["足背动脉搏动消失"] = "获取出错"
                        else:
                            suifang_data["足背动脉搏动触及正常"] = None
                            suifang_data["足背动脉搏动减弱"] = None
                            suifang_data["足背动脉搏动消失"] = None

                        # 肺结核相关症状检查
                        try:
                            # 是否糖尿病
                            diabetes_selected = tree.xpath(
                                '//input[@name="TUBERCULOSIS.isDiabetesMellitus" and @checked="checked"]/@value')
                            if diabetes_selected:
                                diabetes_value = diabetes_selected[0]
                                suifang_data["是否糖尿病"] = "是" if diabetes_value == "1" else "否"
                            else:
                                suifang_data["是否糖尿病"] = None
                        except:
                            suifang_data["是否糖尿病"] = "获取出错"

                        try:
                            # 是否老年人
                            old_selected = tree.xpath('//input[@name="TUBERCULOSIS.isOld" and @checked="checked"]/@value')
                            if old_selected:
                                old_value = old_selected[0]
                                suifang_data["是否老年人"] = "是" if old_value == "1" else "否"
                            else:
                                suifang_data["是否老年人"] = None
                        except:
                            suifang_data["是否老年人"] = "获取出错"

                        try:
                            # 是否咳嗽、咳痰2周
                            cough_selected = tree.xpath('//input[@name="TUBERCULOSIS.isCough" and @checked="checked"]/@value')
                            if cough_selected:
                                cough_value = cough_selected[0]
                                suifang_data["是否咳嗽、咳痰≥2周"] = "是" if cough_value == "1" else "否"
                            else:
                                suifang_data["是否咳嗽、咳痰≥2周"] = None
                        except:
                            suifang_data["是否咳嗽、咳痰≥2周"] = "获取出错"

                        try:
                            # 是否痰中带血或咯血
                            hemoptysis_selected = tree.xpath(
                                '//input[@name="TUBERCULOSIS.isHemoptysis" and @checked="checked"]/@value')
                            if hemoptysis_selected:
                                hemoptysis_value = hemoptysis_selected[0]
                                suifang_data["是否痰中带血或咯血"] = "是" if hemoptysis_value == "1" else "否"
                            else:
                                suifang_data["是否痰中带血或咯血"] = None
                        except:
                            suifang_data["是否痰中带血或咯血"] = "获取出错"

                        # 评估
                        try:
                            assess_content = tree.xpath('//textarea[@name="assess"]/text()')
                            if assess_content:
                                content = assess_content[0].strip()
                                suifang_data["评估"] = content if content else None
                            else:
                                suifang_data["评估"] = None
                        except:
                            suifang_data["评估"] = "获取出错"

                        # 生活方式
                        try:
                            lifestyle_content = tree.xpath('//textarea[@id="lifestyle"]/text()')
                            if lifestyle_content:
                                # 连接所有文本节点并处理换行符
                                content = ''.join(lifestyle_content).strip()
                                # 将换行符替换为空格，并去除多余空格
                                content_no_newline = ' '.join(content.replace('\n', ' ').replace('\r', ' ').split())
                                suifang_data["生活方式"] = content_no_newline if content_no_newline else None
                            else:
                                suifang_data["生活方式"] = None
                        except:
                            suifang_data["生活方式"] = "获取出错"

                        # 医生建议
                        try:
                            suggest_content = tree.xpath('//textarea[@id="suggest"]/text()')
                            if suggest_content:
                                content = ''.join(suggest_content).strip()
                                content_no_newline = ' '.join(content.replace('\n', ' ').replace('\r', ' ').split())
                                suifang_data["医生建议"] = content_no_newline if content_no_newline else None
                            else:
                                suifang_data["医生建议"] = None
                        except:
                            suifang_data["医生建议"] = "获取出错"

                        # 获取flwId

                        script_texts = tree.xpath('//script/text()')
                        flw_id = None
                        import re
                        for script_text in script_texts:
                            match = re.search(r"var flwId\s*=\s*'([^']+)'", script_text)
                            if match:
                                flw_id = match.group(1)
                                break

                        # 用药情况""
                        yongyao_url = f"{DOMAIN}/phis/app/svc/flw/take/med"
                        data = {
                            'flwId': f'{flw_id}',
                            '_dch': '1756276734374',
                        }
                        yongyao_list = []

                        response_yongyao = requests.post(yongyao_url, data=data,headers=headers_8).json()

                        for li in response_yongyao["content"]:
                            yongyao_dict = {}
                            yongyao_dict["用药名称"] = li["medName"]
                            yongyao_dict["用法"] = li["methodVolume"]
                            yongyao_dict["用量"] = li["useLevel"]
                            yongyao_list.append(yongyao_dict)
                        suifang_data["用药情况"] = yongyao_list
                        all_infomation.append(suifang_data)

        return all_infomation # 返回完整数据和提取的数据

    except:
        print(f"处理失败: {id_person}, 错误: 获取信息时报错了")
        return None






if __name__ == '__main__':
    headers_8 = {
        'Cookie': 'JSESSIONID=9B09F4B7F6E0A26E978767BFA8A7C3CA',
    }
    print(suifangdownload1("110229197909064227","bc8b6214-1d82-422f-9623-345cabac3b96",headers_8,"http://10.174.166.48:8082","2025-01-01","2025-12-31",{"随访类型":"高血压,糖尿病"}))
